package com.zhonglz.system.controller;


import com.zhonglz.service.SysUserService;
import com.zhonglz.util.md5.SSOMd5Utils;
import com.zhonglz.util.result.ResultUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping("/home")
public class TestController {


    @Autowired
    private SysUserService sysUserService;


    /***
     * 服务端认证接口地址
     */
    private final static String authUrl = "http://127.0.0.1:9091/tocc/api/auth/v1/ticket/verify";
    /***
     * 授权码
     */
    private final static String authCode = "87d193cb2df64e6f";

    /***
     * 授权密码
     */
    private final static String authPsw = "5e1a17dd71e347998b49a7f7";

    /**
     * 握手认证请求体
     */
    @Data
    public static class TokenAuthDTO {
        /** 认证token，此处用code 命名  */
        private String code;
        /** 时间戳 String.valueOf(System.currentTimeMillis()) */
        private String timestamp;
        /** 认证令牌 */
        private String ticket;
    }

    /***
     * 模拟单点登录进来的双向认证接口
     * @param model
     * @return
     */
    @PostMapping("/index")
    public ResultUtils index(@RequestBody TokenAuthDTO  model) {
        String token = model.code;
        System.out.println("获取到token:"+token);
        /// 1.第一步根据接收到的model实体，先验证传递过来的token验证是否篡改
        String ticket = SSOMd5Utils.createTicketValue(token,model.timestamp);
        // 验证摘要是否一致
        if (!ticket.equals(model.ticket)) {
            System.out.println("握手ticket验证失败！");
            throw new RuntimeException("握手ticket验证失败！");
        }
        /// 2.第二步根据授权码，授权密码，时间戳生成相对应的双向认证ticket进行请求验证
        // 获取当前时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        // 生成双向认证ticket
        String twoWayTicket =SSOMd5Utils.createTicketValue(authCode,authPsw,ticket,timestamp);
        // 构造请求参数
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        /// 组装二次请求体
        Map<String, Object> params = new java.util.HashMap<>();
        params.put("code", token);
        params.put("authCode", authCode);
        params.put("timestamp", timestamp);
        params.put("ticket",  ticket);
        params.put("twoWayTicket", twoWayTicket);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
        String ss;
        try {
            /// 3.发送请求得到相对应的请求结果
            ResponseEntity<String> response = restTemplate.postForEntity(authUrl, request, String.class);
            System.out.println("请求结果: " + response.getBody());
            ss = response.getBody();
        } catch (Exception e) {
            throw new RuntimeException("请求授权平台失败: " + e.getMessage());
        }
        // 校验返回结果
        try {
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            Map<String, Object> respMap = objectMapper.readValue(ss, Map.class);
            Object codeObj = respMap.get("code");
            if (codeObj != null && "0".equals(codeObj.toString())) {
                // 验证成功后，模拟登录返回给前端
                ResultUtils result = sysUserService.login("admin", "admin123456");
                return result;
            } else {
                return new ResultUtils(ResultUtils.CODE_EXCEPTION,"校验信息不成功: " + respMap.getOrDefault("msg", "未知错误"));
            }
        } catch (Exception e) {
            return new ResultUtils(ResultUtils.CODE_EXCEPTION,"响应解析失败: " + e.getMessage());
        }
    }



}